package com.kk.utils;
/*
    自己手动封装的工具类,在这里面通过oss完成文件上传,并返回上传后的文件路径
 */


import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

@Component
public class MyAliYunOssUtils {

    @org.springframework.beans.factory.annotation.Value("${aly.endpoint}")
    private String endpoint;

    @org.springframework.beans.factory.annotation.Value("${aly.bucketName}")
    private String bucketName;

    @org.springframework.beans.factory.annotation.Value("${aly.region}")
    private String region;

    public String upload(String filename, byte[] bytes) {

        OSS ossClient = null;
        try {
            // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量
            EnvironmentVariableCredentialsProvider credentialsProvider =
                    CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

            // 创建 OSSClient 实例
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            // 显式声明使用 V4 签名算法
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
            ossClient = OSSClientBuilder.create()
                    .endpoint(endpoint)
                    .credentialsProvider(credentialsProvider)
                    .region(region)
                    .build();
            // 2. 上传文件
            ossClient.putObject(bucketName, filename, new ByteArrayInputStream(bytes));
            System.out.println("2. 文件 " + filename + " 上传成功。");
            // 拼接出一个上传后的文件路径
            StringBuilder stringBuilder = new StringBuilder("https://");
            String url = stringBuilder.append(bucketName)
                    .append(".")
                    .append(endpoint)
                    .append("/")
                    .append(filename).toString();
            return url;
        } catch (Exception oe) {
            oe.printStackTrace();
            throw new RuntimeException("文件上传失败了,请检查文件上传的过程....");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
